package ynu.edu.achitectureclass.service.SoilSensorService;

import ynu.edu.achitectureclass.entity.Device;
import ynu.edu.achitectureclass.entity.Soil_K;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ynu.edu.achitectureclass.repository.Soil_K_Reposotory;
import ynu.edu.achitectureclass.service.BaseSensorService;
import ynu.edu.achitectureclass.service.SensorService;


import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.*;
@Service
public class Soil_K_Service extends BaseSensorService<Soil_K> implements SensorService<Soil_K> {

    @Autowired
    private Soil_K_Reposotory soilKReposotory;

    @Transactional
    public void storeSoilData(Object data) {
        // 解析返回的数据并存储
        if (data instanceof List) {  // 确保数据是一个列表
            List<Map<String, Object>> dataList = (List<Map<String, Object>>) data;
            System.out.println(dataList);
            for (Map<String, Object> dataMap : dataList) {
                System.out.println(dataMap);

                String sensorSerialNumber = (String) dataMap.get("id");
                String name = (String) dataMap.get("name");
                Double value = (Double) dataMap.get("value");
                String timestamp = (String) dataMap.get("timestamp");

                Optional<Device> deviceOpt = deviceRepository.findBySerialNumber(sensorSerialNumber);
                if (!deviceOpt.isPresent()) {
                    throw new IllegalArgumentException("Device with serial number " + sensorSerialNumber + " not found");
                }
                Device device = deviceOpt.get();
                System.out.println(device);

                Soil_K soilK = new Soil_K();
                soilK.setDeviceId(device.getId());
                soilK.setName(name);
                soilK.setValue(value);
                LocalDateTime createdAt = LocalDateTime.parse(timestamp.replace("Z", ""));
                soilK.setCreatedAt(createdAt);

                soilKReposotory.save(soilK);
            }
        } else {
            throw new IllegalArgumentException("Invalid data format.");
        }
    }

    @Override
    public Soil_K getLatestData() {
        return (Soil_K) soilKReposotory.findTopByOrderByCreatedAtDesc()
                .orElseThrow(() -> new IllegalArgumentException("No air temperature data found."));
    }

    @Override
    public List<Soil_K> getAllData() {
        return soilKReposotory.findAll();
    }


}
